package pack1;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.swim.entity.RegisteredUser;
import com.swim.session.RegisteredUserRemote;

public class FriendsListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
      
    
    public FriendsListServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    	HttpSession session = request.getSession();
    	if(session.getAttribute("authenticated") == null || !(boolean)session.getAttribute("authenticated")) {
    		response.sendRedirect("index.jsp");
			return;
    	}

    	List<RegisteredUser> friends = getFriendsList((String) session.getAttribute("authenticated-email"));
		request.setAttribute("friends", friends);
		RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/auth/friends.jsp");
		dispatcher.forward(request, response);
    }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	if(request.getSession().getAttribute("authenticated") == null || !(boolean)request.getSession().getAttribute("authenticated")) {
    		response.sendRedirect("index.jsp");
			return;
    	}
    	HttpSession session = request.getSession();
    	
    	List<RegisteredUser> friends = getFriendsList((String) session.getAttribute("authenticated-email"));
		request.setAttribute("friends", friends);
		RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/auth/friends.jsp");
		dispatcher.forward(request, response);
		
    }

	private List<RegisteredUser> getFriendsList(String email) {
		try {
			
			InitialContext jndiContext = (InitialContext) Util.getInitialContext();
			Object ref = jndiContext.lookup("RegisteredUserBeanJNDI");
			RegisteredUserRemote r = (RegisteredUserRemote) ref;
			
			List<RegisteredUser> results = new ArrayList<RegisteredUser>();
			results.addAll(r.getFriendsOf(email));
			return results;
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
}
